package xml;

import android.Manifest;
import android.app.ActionBar;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.VideoView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatButton;
import androidx.appcompat.widget.AppCompatEditText;
import androidx.appcompat.widget.AppCompatImageView;
import androidx.core.content.FileProvider;

import com.example.application.R;
import com.example.application.activity.MainActivity;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.XXPermissions;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import org.json.JSONObject;

import java.io.File;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static com.example.application.activity.ToastUtil.*;

public class LoginActivity extends AppCompatActivity {
    private AppCompatEditText usernameEditText;
    private AppCompatEditText passwordEditText;
    private AppCompatButton loginButton;
    private AppCompatButton cameraButton;
    private AppCompatButton camera1Button;
    private AppCompatButton cropButton;
    private AppCompatButton videoButton;
    private AppCompatButton video1Button;
    private AppCompatButton movieButton;
    private AppCompatImageView mainImageView;
    private VideoView mainVideoView;


    private File file;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        usernameEditText = findViewById(R.id.mobileEditText);
        passwordEditText = findViewById(R.id.passwordEditText);
        loginButton = findViewById(R.id.loginButton);
        cameraButton = findViewById(R.id.cameraButton);
        camera1Button = findViewById(R.id.camera1Button);
        mainImageView = findViewById(R.id.mainImageView);
        cropButton = findViewById(R.id.cropButton);

        videoButton = findViewById(R.id.videoButton);
        video1Button = findViewById(R.id.video1Button);
        mainImageView = findViewById(R.id.mainImageView);

        mLocationClient = new LocationClient(getApplicationContext());
        mLocationClient.registerLocationListener(myListener);
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        option.setCoorType("bd09ll");
        option.setScanSpan(1000);
        option.setOpenGps(true);
        option.setLocationNotify(true);
        mLocationClient.setLocOption(option);
        mLocationClient.start();//开始定位，重要的方法，如果不执行就不会定位

        ArrayList<String> files = getFilesAllName("/storage/emulated/0/Movies");
        for (int i = 0; i < files.size(); i++) {
            if (files.get(i).contains("123.mp4")) {
                File file = new File(files.get(i));
                mainImageView.setVideoURI(Uri.fromFile(file));
                mainImageView.start();

            }
        }

        String key = MyApp1.get().getSharedPreferences().getString("key", "");
        if (!key.isEmpty()) {
            startActivity(new Intent(LoginActivity.this, MainActivity.class));
            finish();
        }

        loginButton.setOnClickListener(view -> {
            String mobile = usernameEditText.getText().toString();
            String password = passwordEditText.getText().toString();
            if (mobile.isEmpty() || password.isEmpty()) {
                ToastUtil.show(this, "请输入手机号或密码");
                return;
            }
            if (!isMobileNO(mobile)) {
                show(this, "请输入有效手机号");
                return;
            }
            if (password.length() < 6) {
                show(this, "密码长度不对");
                return;
            }
            OkGo.<String>post("https://demo.shopwt.com/api/mobile/index.php?w=login")
                    .params("username", mobile)
                    .params("password", password)
                    .params("client", "wap")
                    .execute(new StringCallback() {
                        @Override
                        public void onSuccess(Response<String> response) {
                            try {
                                JSONObject jsonObject = new JSONObject(response.body().toString());
                                if (jsonObject.getInt("code") == 400) {
                                    jsonObject = jsonObject.getJSONObject("datas");
                                    show(LoginActivity.this, jsonObject.getString("error"));
                                    return;
                                }
                                jsonObject = jsonObject.getJSONObject("datas");
                                String key = jsonObject.getString("key");
                                MyApp1.get().getEditor().putString("key", key).apply();
                                show(LoginActivity.this, "登录成功~");
                                startActivity(new Intent(LoginActivity.this, MainActivity.class));
                                finish();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });
        });

        cameraButton.setOnClickListener(view -> {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(intent, 999);
        });

        camera1Button.setOnClickListener(view -> {
            file = FileUtil.createFile(
                    getExternalMediaDirs()[0].getAbsolutePath(),
                    "learn2",
                    "jpg"
            );
            if (file != null) {
                Uri uri = FileProvider.getUriForFile(this, "top.yokey.learn2.fileProvider", file);
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                startActivityForResult(intent, 1000);
            }
        });

        cropButton.setOnClickListener(view -> {
            Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            intent.setType("image/*");
            startActivityForResult(intent, 1001);
        });

        //调用系统相册选择视频并播放
        videoButton.setOnClickListener(view -> {
            Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            intent.setType("video/*");
            startActivityForResult(intent, 1003);
        });

        //调用系统相机录制视频并播放
        video1Button.setOnClickListener(view -> {
            Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
            startActivityForResult(intent, 1004);
        });


        public boolean isMobileNO (String mobiles){
            Pattern p = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");
            Matcher m = p.matcher(mobiles);
            return m.matches();
        }

        private ArrayList<String> getFilesAllName (String path){
            File file = new File(path);
            File[] files = file.listFiles();
            if (files == null) {
                return null;
            }
            ArrayList<String> list = new ArrayList<>();
            for (int i = 0; i < files.length; i++) {
                list.add(files[i].getAbsolutePath());
            }
            return list;
        }

        @Override
        protected void onResume () {
            super.onResume();
            String[] permission = new String[]{
                    Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.READ_CONTACTS,
                    Manifest.permission.READ_SMS,
                    Manifest.permission.READ_CALL_LOG,
                    Manifest.permission.CAMERA,
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
            };
            XXPermissions.with(this).permission(permission).request(new OnPermissionCallback() {
                @Override
                public void onGranted(List<String> permissions, boolean all) {
                    //用户允许权限申请
                }

                @Override
                public void onDenied(List<String> permissions, boolean never) {
                    //用户拒绝了权限申请
                    ToastUtil.show(LoginActivity.this, "用户拒绝了读取通讯录的权限");
                }
            });

        }

        @Override
        protected void onActivityResult ( int requestCode, int resultCode, @Nullable Intent data){
            super.onActivityResult(requestCode, resultCode, data);
            if (resultCode == RESULT_OK) {
                if (requestCode == 999) {
                    Bitmap bitmap = data.getExtras().getParcelable("data");
                    mainImageView.setImageBitmap(bitmap);
                }
                if (requestCode == 1000) {
                    Log.d("TAGS", mPhotoFile.getAbsolutePath());
                    mainImageView.setImageURI(Uri.fromFile(mPhotoFile));
                    FileUtil.showInAlbum(this, mPhotoFile.getAbsolutePath());
                }
                if (requestCode == 1001) {
                    mPhotoFile = FileUtil.createFile(
                            getExternalMediaDirs()[0].getAbsolutePath(),
                            "learn2",
                            "jpg"
                    );
                    Intent cropIntent = new Intent("com.android.camera.action.CROP");//跳到系统裁剪界面
                    cropIntent.setDataAndType(data.getData(), "image/*");//设置裁剪图片的数据源
                    cropIntent.putExtra("crop", "true");//设置裁剪
                    cropIntent.putExtra("aspectX", 1);
                    cropIntent.putExtra("aspectY", 1);
                    cropIntent.putExtra("outputX", 500);
                    cropIntent.putExtra("outputY", 500);
                    cropIntent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
                    cropIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.parse("file://" + mPhotoFile.getAbsolutePath()));
                    cropIntent.putExtra("return-data", "false");
                    startActivityForResult(cropIntent, 1002);
                    FileUtil.showInAlbum(this, mPhotoFile.getAbsolutePath());
                }
                if (requestCode == 1002) {
                    mainImageView.setImageURI(Uri.fromFile(mPhotoFile));
                }
                if (requestCode == 1003) {
                    Uri uri = data.getData();
                    mainVideoView.setVideoURI(uri);
                    mainVideoView.start();
                }
                if (requestCode == 1004) {
                    Uri uri = data.getData();
                    mainVideoView.setVideoURI(uri);
                    mainVideoView.start();
                }
            }
        }

        class MyLocationListener extends BDAbstractLocationListener {
            @Override
            public void onReceiveLocation(BDLocation location) {
                //此处的BDLocation为定位结果信息类，通过它的各种get方法可获取定位相关的全部结果
                //以下只列举部分获取经纬度相关（常用）的结果信息
                //更多结果信息获取说明，请参照类参考中BDLocation类中的说明

                double latitude = location.getLatitude();    //获取纬度信息
                double longitude = location.getLongitude();    //获取经度信息
                float radius = location.getRadius();    //获取定位精度，默认值为0.0f

                String coorType = location.getCoorType();
                //获取经纬度坐标类型，以LocationClientOption中设置过的坐标类型为准

                int errorCode = location.getLocType();
                //获取定位类型、定位错误返回码，具体信息可参照类参考中BDLocation类中的说明

                Log.d("TAGS", errorCode + "|" + latitude + "|" + longitude);

            }
        }
    }
    
